<?php
class stFlickrToolboxController extends stcontroller_2_1 {
	
	public function __construct($config) {
		parent::__construct ( $config );
	}
	
	public function loadAdminCss(){
            echo '<link href="' . $this->config ['backendCss'] . 'prettyphoto/prettyPhoto.css" rel="stylesheet" type="text/css" />' . "\n";
        }

        public function loadAdminScript(){
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.prettyPhoto.js"></script>';
            echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stcustom.js"></script>';
        }

        public function loadCss(){
            //this is function import javascript
            parent::loadCss();
        }

        public function loadScript(){
            //this is function import javascript
            parent::loadScript();            
        }

        public function activationPlugin() {
            // put your activation code here
            global $wpdb;
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            
            
            $table = $wpdb->prefix."st_flickr";
            $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `photo_id` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `series` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `visibility` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `title` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `description` text COLLATE utf8_unicode_ci DEFAULT NULL,
              `tag` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `numviews` int(11) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
            ";
            dbDelta($structure);

            $table = $wpdb->prefix."st_flickr_set_photo";
            $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `photo_id` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `set_id` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
            ";
            dbDelta($structure);

            $table = $wpdb->prefix."st_flickr_set";
            $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `set_id` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `title` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `description` text COLLATE utf8_unicode_ci DEFAULT NULL,
              `primary` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `series` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
            ";
            dbDelta($structure);
        }

        public function deactivationPlugin() {
            // put your deactivation code here
//            global $wpdb;
//            $table = $wpdb->prefix."st_stFlickrToolbox";
//            $query = "DROP TABLE $table";
//            $wpdb->query($query);
        }

        public function registerView(){
            $views = array(
                'menu_child1'       => 'default_theme',
                //you can call this action by use these urls:
                // 1.   home_url/menu_child1
                // 2.   home_url/?page=plugin_name&action=menu_child1
                // 3.   home_url/?page=plugin_name&action=menu_child1&ajax=1
                'menu_child2'       => 'default_theme'
                );
            $this->setView($views);
        }

        public function flickrSetting() {
            $option = $this->option;
            $option['flickr_key'] = empty($option['flickr_key'])? $this->config['default_flickr_key']:$option['flickr_key'];
            $option['flickr_secret'] = empty($option['flickr_secret'])? $this->config['default_flickr_secret']:$option['flickr_secret'];
            $option['flickr_user_id'] = empty($option['flickr_user_id'])? $this->config['default_flickr_user_id']:$option['flickr_user_id'];
            
            //initialize variable to view
            $this->view->option = $option;
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'Flickr settings';
            if($_POST['handle']){
                $flickr_key = isset($_POST['flickr_key'])? $_POST['flickr_key']:$option['flickr_key'];
                $flickr_secret = isset($_POST['flickr_secret'])? $_POST['flickr_secret']:$option['flickr_secret'];
                $flickr_user_id = isset($_POST['flickr_user_id'])? $_POST['flickr_user_id']:$option['flickr_user_id'];
                $flickr_token = isset($_POST['flickr_token'])? $_POST['flickr_token']:$option['flickr_token'];

                $data = array(
                    'flickr_key' => $flickr_key,
                    'flickr_secret' => $flickr_secret,
                    'flickr_user_id' => $flickr_user_id,
                    'flickr_token' => $flickr_token
                );
                $this->updateOption($data);
                require_once $this->config['pluginDir'].'stFlickrToolboxclass.php';
                $stFlickrToolbox = new stFlickrToolboxclass($this->config, $option);
                $stFlickrToolbox->auth();
            }
	}

        public function flickrPhotostream() {
            $stFlickrToolbox_model = $this->loadmodel ( "stflickr" );
            $user_id = get_current_user_id();
            if($_POST['sync'] == 1){
                require_once $this->config['pluginDir'].'stFlickrToolboxclass.php';
                $stFlickrToolbox = new stFlickrToolboxclass($this->config, $this->option);
                $stFlickrToolbox->syncPhoto();
            }

            // short action handleAND
            if($_REQUEST['short_action'] == 'delete'){
                $id = $_REQUEST['id'];                
                $args = array();
                $args['fields'] = array('photo.*, settable.title settitle');
                $args['where'] = "photo.id=$id";
                $results = $stFlickrToolbox_model->getRecords($args);
                $data = $results[0];
                $photo_id = $data->photo_id;

                require_once $this->config['pluginDir'].'stFlickrToolboxclass.php';
                $stFlickrToolbox = new stFlickrToolboxclass($this->config, $this->option);
                if($stFlickrToolbox->flickr->photos_delete($photo_id)){
                    if($stFlickrToolbox_model->deleteRecords($_REQUEST['id']))
                        echo stfunctions_2_1::sendMessage(__('Delete successful', $this->config['plugin_name']));
                    else
                        echo stfunctions_2_1::sendMessage(__('Delete fail', $this->config['plugin_name']));
                }


            }

            $args = array();
            $args['fields'] = array('photo.*, settable.title settitle');
            $cur_page = $_REQUEST['cur_page']? $_REQUEST['cur_page']:1;
            $limit = $this->config['per_page'];
            $start = ($cur_page-1) * $limit;

            $sort = $_REQUEST['sort']? $_REQUEST['sort']:0;
            $sort_type = $_REQUEST['sort_type']? $_REQUEST['sort_type']:0;
            if($_REQUEST['sort']){
                $args['order'] = array($sort, $sort_type);
            }
            $args['limit'] = array($start, $limit);
            $args['group_by'] = 'photo.id';
            $args['where'] = " photo.user_id= $user_id";
            if($_REQUEST['short_action'] == 'show_photo' || !empty($_POST['set_id'])){
                $set_id = empty($_REQUEST['id'])? $_POST['set_id']:$_REQUEST['id'];
                $where = ' AND settable.id = '.$set_id;
                $args['where'] = $where;
            }

            $results = $stFlickrToolbox_model->getRecords($args);
            $args['limit'] = array();            
            $total = $stFlickrToolbox_model->countRecords($args);
            $stFlickrToolboxFunctions = new stFlickrToolboxFunctions($this->config);
            $pagination = $stFlickrToolboxFunctions->pagination($start, $limit, $total, $cur_page, $this->actionName);

            $columns = array(
                //'photo_id'  => __('Photo ID', $this->config['plugin_name']),
                //'series'  => __('Series', $this->config['plugin_name']),
                'title'         => __('Title', $this->config['plugin_name']),
                'thumbnail_url' => __('Images', $this->config['plugin_name']),
                'settitle'      => __('Set', $this->config['plugin_name']),
                'photo_id'  => __('Publish to', $this->config['plugin_name']),
                //'description'   => __('Description', $this->config['plugin_name']),
                //'tag'           => __('Tags', $this->config['plugin_name']),
                //'status'    => __('View', $this->config['plugin_name']),
                //'permaLink' => __('Playlist', $this->config['plugin_name']),
                //'numviews'      => __('Views', $this->config['plugin_name'])
            );
            register_column_headers('stFlickrToolbox_st_flickr', $columns);

            //initialize variable to view
            $this->view->results = $results;
            $this->view->permission = $this->functions->getPermission();
            $this->view->permission_twitter = $this->functions->getPermission('stTwitterToolbox');
            $this->view->option_facebook = get_option("wall_publish_option");
            $this->view->option_twitter = $this->functions->cronjob_get_option('stTwitterToolbox_1_settings', $user_id);
            $this->view->option = $this->option;
            $this->view->pagination = $pagination;
            $this->view->set_id = $set_id;
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'Photo lists';
            $this->view->iconNew = 'Update Photos';
            $this->view->viewNew = 'flickrPhotostream';
            $this->view->dataNew = array('sync'  => 1);
            $arg = array(
                'status'    => 'success',
                'message'   => __('Update photo successful', $config['plugin_name'])
            );
            $this->view->messageNew = json_encode($arg);
	}

        public function flickrEdit() {
            require_once $this->config['pluginDir'].'stFlickrToolboxclass.php';
            $stFlickrToolbox = new stFlickrToolboxclass($this->config, $this->option);

            $stFlickrToolbox_model = $this->loadmodel ( "stflickr" );
            if(isset($_REQUEST['id'])){
                $id = $_REQUEST['id'];
                $args = array();
                $args['fields'] = array('photo.*, settable.title settitle');
                $args['where'] = "photo.id=$id";
                $results = $stFlickrToolbox_model->getRecords($args);
            }
            $result = $results[0];

            $photo_info = $stFlickrToolbox->getPhotoInfo($result->photo_id);
            $result->description = $photo_info['description'];
            $tag_tmp = array();
            if(count($photo_info['tags']['tag']) >0){
                foreach ($photo_info['tags']['tag'] as $tag) {
                    $tag_tmp[] = $tag['raw'];
                }
            }

            $result->tag = implode(',', $tag_tmp);

            //initialize variable to view
            $this->view->result = $result;
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'Edit video';

            // Handle post
            if($_POST['data']){

                $data = $_POST['data'];
                $photo_id = $data['photo_id'];
                $stFlickrToolbox->flickr->photos_setMeta($photo_id, $data['title'], $data['description']);
                $stFlickrToolbox->flickr->photos_setTags($photo_id, $data['tag']);
                $stFlickrToolbox_model->saveRecords($data);
            }
	}

        public function flickrSet() {
            $stFlickrToolbox_set_model = $this->loadmodel ( "stflickr_set" );
            $user_id = get_current_user_id();
            // short action handle
            if($_REQUEST['short_action'] == 'delete'){
                $id = $_REQUEST['id'];
                $args = array();
                $args['where'] = "id=$id";
                $results = $stFlickrToolbox_set_model->getRecords($args);
                $data = $results[0];
                $set_id = $data->set_id;

                require_once $this->config['pluginDir'].'stFlickrToolboxclass.php';
                $stFlickrToolbox = new stFlickrToolboxclass($this->config, $this->option);
                if($stFlickrToolbox->flickr->photosets_delete($set_id)){
                    if($stFlickrToolbox_set_model->deleteRecords($_REQUEST['id']))
                        echo stfunctions_2_1::sendMessage(__('Delete successful', $this->config['plugin_name']));
                    else
                        echo stfunctions_2_1::sendMessage(__('Delete fail', $this->config['plugin_name']));
                }


            }

            $args = array();
            $cur_page = $_REQUEST['cur_page']? $_REQUEST['cur_page']:1;
            $limit = $this->config['per_page'];
            $start = ($cur_page-1) * $limit;

            $sort = $_REQUEST['sort']? $_REQUEST['sort']:0;
            $sort_type = $_REQUEST['sort_type']? $_REQUEST['sort_type']:0;
            if($_REQUEST['sort']){
                $args['order'] = array($sort, $sort_type);
            }
            $args['limit'] = array($start, $limit);
            $args['group_by'] = 'id';
            $args['where'] = " user_id= $user_id";

            $results = $stFlickrToolbox_set_model->getRecords($args);
            $args['limit'] = array();
            $total = $stFlickrToolbox_set_model->countRecords($args);
            $stFlickrToolboxFunctions = new stFlickrToolboxFunctions($this->config);
            $pagination = $stFlickrToolboxFunctions->pagination($start, $limit, $total, $cur_page, $this->actionName);

            $columns = array(
                //'photo_id'  => __('Photo ID', $this->config['plugin_name']),
                //'series'  => __('Series', $this->config['plugin_name']),
                'title'         => __('Title', $this->config['plugin_name']),               
                'description'   => __('Description', $this->config['plugin_name']),
                'primary'       => __('Images', $this->config['plugin_name']),
                //'status'    => __('View', $this->config['plugin_name']),
                //'permaLink' => __('Playlist', $this->config['plugin_name']),
                //'numviews'      => __('Views', $this->config['plugin_name'])
            );
            register_column_headers('stFlickrToolbox_st_flickr_set', $columns);

            //initialize variable to view
            $this->view->results = $results;
            $this->view->pagination = $pagination;
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'Sets lists';
	}

        public function flickrSetEdit() {
            require_once $this->config['pluginDir'].'stFlickrToolboxclass.php';
            $stFlickrToolbox = new stFlickrToolboxclass($this->config, $this->option);

            $stFlickrToolbox_set_model = $this->loadmodel ( "stflickr_set" );
            if(isset($_REQUEST['id'])){
                $id = $_REQUEST['id'];
                $args = array();
                $args['where'] = "id=$id";
                $results = $stFlickrToolbox_set_model->getRecords($args);
            }
            $result = $results[0];

            //initialize variable to view
            $this->view->result = $result;
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'Edit set';

            // Handle post
            if($_POST['data']){

                $data = $_POST['data'];
                $set_id = $data['set_id'];
                $stFlickrToolbox->flickr->photosets_editMeta($set_id, $data['title'], $data['description']);
                $stFlickrToolbox_set_model->saveRecords($data);
            }
	}

        public function flickrUpload() {
            $this->view->headIcon = 'icon_re';
            $this->view->headTitle1 = 'Upload Photo';
            if($_POST['data']){
                $stFlickrToolbox_model = $this->loadmodel ( "stflickr" );
                require_once $this->config['pluginDir'].'stFlickrToolboxclass.php';
                $data = $_POST['data'];

                //$data['src'] = $_FILES['src'];
                $filename = $_FILES['src'];
                $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);

                $override['test_form'] = false;
                $override['action'] = 'wp_handle_upload';
                $uploaded_file = wp_handle_upload($filename, $override);
                //$data['src'] = $uploaded_file['file'];
                //var_dump($uploaded_file);die;
                $stFlickrToolbox = new stFlickrToolboxclass($this->config, $this->option);
                $photo_id = $stFlickrToolbox->flickr->sync_upload($uploaded_file['file'], $data['title'], $data['description'], $data['tag'], 1);
                $photo_info = $stFlickrToolbox->getPhotoInfo($photo_id);
                if(!empty($photo_info)){
                    $photos = array($photo_info);
                    $stFlickrToolbox_model->savestFlickrToolbox($photos);
                    echo '<script type="text/javascript">';
                    echo "stFlickrToolbox.loadPage('flickrPhotostream', '', '" . __("Successful", $this->config['plugin_name']) . "', function(){
                        stFlickrToolbox.showSideMenu('flickrPhotostream');
                    });";
                    echo '</script>';
                }
            }
	}

}
?>